<script setup lang='ts'>
import { cloneDeep } from 'lodash-es'
import { ref, toRefs } from 'vue'

import AddRuleCalc from './add-rule-calc.vue'
import AddRulePricing from './add-rule-pricing.vue'

const props = withDefaults(defineProps<{
    data?: any
}>(), {})

const emits = defineEmits(['cancel'])
const { data } = toRefs(props)
const pricRef = ref()
const ruleRef = ref()

const activeTab = ref(0)
const showTab = ref(0)

const tabsList = [
    {
        label: '报价清单',
        value: 0,
    },
    {
        label: '计算规则',
        value: 1,
    },
]

function doSave() {
    if (activeTab.value === 1) {
        ruleRef.value.doSave(doCancel)
    }
    else {
        pricRef.value.doSave(doCancel)
    }
}

function doCancel() {
    emits('cancel')
}

function tabChange(val: any) {
    const name = cloneDeep(activeTab.value)
    const nextName = val.props.name

    if (hasDraft()) {
        ElMessageBox.confirm('存在未保存修改，切换将丢失，是否继续切换?', '提示', { type: 'warning' })
            .then(() => {
                showTab.value = nextName
            }).catch(() => {
                activeTab.value = name
            })
    }
    else {
        showTab.value = nextName
    }
}

// 检测是否存在未保存数据
function hasDraft() {
    let flag = false
    if (showTab.value === 1) {
        flag = ruleRef.value.hasDraft()
    }
    else {
        flag = pricRef.value.hasDraft()
    }
    return flag
}

defineExpose({
    hasDraft,
})
</script>

<template>
    <el-tabs v-model="activeTab"
             @tab-click="tabChange"
    >
        <el-tab-pane v-for="item in tabsList"
                     :key="item.value"
                     :label="item.label"
                     :name="item.value"
        />
    </el-tabs>

    <AddRulePricing v-if="showTab === 0"
                    :id="data"
                    ref="pricRef"
    />

    <AddRuleCalc v-if="showTab === 1"
                 :id="data"
                 ref="ruleRef"
    />

    <div class="mt-20 text-center w-full">
        <el-button type="primary"
                   @click="doSave"
        >
            保存
        </el-button>

        <el-button @click="doCancel">
            取消
        </el-button>
    </div>
</template>

<style lang="scss" scoped></style>
